﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MedicalCare.EntityDefinitions.Entities;
using MedicalCare.Messages;
using MedicalCare.Utilities;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;
using StructureMap;

namespace MedicalCare.DbLayer.Adaptors
{
    public class ScheduleAdaptor : IScheduleAdaptor
    {
        private ISession _mcSession;

        public ScheduleAdaptor()
        {
            _mcSession = ObjectFactory.GetNamedInstance<ISession>("MedicalCareSession");
        }

        public int GetRecordsTotal(string whereStr)
        {
            //try
            //{
            //    //var translator = ObjectFactory.GetInstance<IUserInfoToUserMessage>();
            //    var query = _mcSession.CreateSQLQuery(@" EXEC Users_Paging_Total @WHERE=:WHERE ")
            //              .SetString("WHERE", whereStr)
            //              .SetResultTransformer(Transformers.AliasToBean<TotalEntity>());

            //    var result = query.List<TotalEntity>().FirstOrDefault().Total;

            //    return result;
            //}
            //catch (Exception ex)
            //{
            //    //return false;
            //}
            return 0;
        }

        public int Update(ScheduleMessage msg)
        {
            var result = default(int);
            try
            {
                if (msg.Id > 0)// update
                {
                    // TODO: 如果设备id大于0，说明Schedule已存在，则是更新设备信息
                    var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Update  @Id=:Id,@NurseId=:NurseId,@FamilyId=:FamilyId,@StartDT=:StartDT,@EndDT=:EndDT,@Status=:Status,@Details=:Details ")
                                 .SetInt32("Id", msg.Id)
                                 .SetInt32("NurseId", msg.NurseId)
                                 .SetInt32("FamilyId", msg.FamilyId)
                                 .SetDateTime("StartDT", msg.StartDT)
                                 .SetDateTime("EndDT", msg.EndDT)
                                 .SetString("Status", msg.Status)
                                 .SetString("Details", msg.Details)
                                .ExecuteUpdate();
                }
                else // insert
                {
                    // TODO: 如果设备id为空/0，则是插入新Schedule
                    do
                    {

                        var query = _mcSession.CreateSQLQuery(
                            @" EXEC Schedule_Insert  @Id=:Id,@NurseId=:NurseId,@FamilyId=:FamilyId,
                    @ScheduleDay=:ScheduleDay, @StartDT=:StartDT, @EndDT=:EndDT, @Status=:Status, @Details=:Details ")
                            .SetInt32("Id", msg.Id)
                            .SetInt32("NurseId", msg.NurseId)
                            .SetInt32("FamilyId", msg.FamilyId)
                            .SetDateTime("ScheduleDay", msg.ScheduleDay)
                            .SetDateTime("StartDT", msg.StartDT)
                            .SetDateTime("EndDT", msg.EndDT)
                            .SetString("Status", msg.Status)
                            .SetString("Details", msg.Details)
                            .SetResultTransformer(Transformers.AliasToBean<ResultEntity>());
                        var test = query.List<ResultEntity>();
                        result = test.FirstOrDefault().Id;

                        msg.ScheduleDay = msg.ScheduleDay.AddDays(msg.LoopDays);
                        msg.StartDT = msg.StartDT.AddDays(msg.LoopDays);
                        msg.EndDT = msg.EndDT.AddDays(msg.LoopDays);
                    } while (msg.ScheduleDay <= msg.LoopEndDay);
                }
            }
            catch (Exception ex)
            {
                result = -1;
            }

            return result;
        }

        public int UpdateScheduleStatus(ScheduleMessage msg)
        {
            var result = default(int);
            try
            {
                var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Status_Update  @Id=:Id,@Status=:Status ")
                                 .SetInt32("Id", msg.Id)
                                 .SetString("Status", msg.Status)
                                .ExecuteUpdate();
            }
            catch (Exception ex)
            {
                result = -1;
            }

            return result;
        }

        public IList<DateTime> GetAllBookedDatebyMonth(DateTime date)
        {
            var firstDate = new DateTime(date.Year, date.Month, 1);
            var lastDate = firstDate.AddMonths(1).AddSeconds(-1);

            var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Search_BookedDate_ByMonth @FirstDT=:FirstDT, @LastDT=:LastDT ")
                            .SetDateTime("FirstDT", firstDate)
                            .SetDateTime("LastDT", lastDate)
                            .SetResultTransformer(Transformers.AliasToBean<ScheduleEntity>());
            var dateList = query.List<ScheduleEntity>().Select(p => p.ScheduleDay).ToList();

            return dateList;
        }

        public IList<DateTime> GetAllBookedDatebyNurseId(int nurseId)
        {
            var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Search_BookedDate_ByNurseId @NurseId=:NurseId ")
                            .SetInt32("NurseId", nurseId)
                            .SetResultTransformer(Transformers.AliasToBean<ScheduleEntity>());
            var dateList = query.List<ScheduleEntity>().Select(p => p.ScheduleDay).ToList();
            return dateList;
        }
        
        public void Remove(ScheduleMessage message)
        {
            try
            {
                var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Delete @Id=:Id ")
                             .SetInt32("Id", message.Id)
                             .ExecuteUpdate();
            }
            catch (Exception ex)
            {
                //return false;
            }
        }

        public ScheduleMessage Read(string id)
        {
            throw new NotImplementedException();
        }

        public IList<ScheduleEntity> GetSchedule(string orderKey, string orderVal,string whereStr)
        {
            try
            {
               var query  = _mcSession.CreateSQLQuery(@" EXEC Schedule_Get @ORDERKEY=:ORDERKEY, @ORDERVAL=:ORDERVAL, @WHERE=:WHERE ")
                            .SetString("ORDERKEY", orderKey)
                            .SetString("ORDERVAL", orderVal)
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<ScheduleEntity>());
               var scheduleList = query.List<ScheduleEntity>();
                
               return scheduleList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public IList<ScheduleStatusEntity> GetScheduleStatus()
        {
            try
            {
                var statusList = _mcSession.CreateCriteria<ScheduleStatusEntity>()
                   .AddOrder(Order.Asc("DisplayOrder"))
                   .List<ScheduleStatusEntity>();
                return statusList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public IList<ScheduleEntity> GetPagingRecords(string orderKey, string orderVal,
            int pageIndex, int pageSize, string whereStr)
        {
            try
            {
                //var scheduleList = _mcSession.CreateCriteria<ScheduleEntity>()
                //   // .Add(Restrictions.Between("")
                //     .List<ScheduleEntity>()));
                //return scheduleList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public IList<UserRoleEntity> GetAllUserRole()
        {
            try
            {
                // HQL
                var userRoleList = _mcSession.CreateCriteria<UserRoleEntity>()
                     .List<UserRoleEntity>();
                return userRoleList;
            }
            catch (Exception ex)
            {
            }
            return null;
        }

        public IList<FamilyEquipmentEntity>  GetEquipementsByScheduleId(int id)
        {
            try
            {
                var whereStr = "efm.ScheduleId = " + id;
                var query = _mcSession.CreateSQLQuery(@" EXEC User_family_Mapping_Get @WHERE=:WHERE ")
                             .SetString("WHERE", whereStr)
                             .SetResultTransformer(Transformers.AliasToBean<FamilyEquipmentEntity>());
                var familyEquimentsList = query.List<FamilyEquipmentEntity>();
                return familyEquimentsList;
            }
            catch (Exception ex)
            {
                //return false;
            }
            return null;
        }

        public int UpdateFamilyEquipments(List<EquipmentFamilyMappingMessage> msgList)
        {
            var result = default(int);
            if(msgList!=null)
            {
                try
                {
                    var scheduleId = msgList[0].ScheduleId;
                    // delete all
                    //var where = " ScheduleId = " + scheduleId;
                    var delQuery = _mcSession.CreateSQLQuery(@" EXEC Equipment_family_Mapping_Delete @ScheduleId=:Where ")
                            .SetString("Where", scheduleId.ToString())
                            .ExecuteUpdate();


                    // insert for each
                    foreach (var msg in msgList)
                    {

                        var insertQuery = _mcSession.CreateSQLQuery(
                                @" EXEC Equipment_family_Mapping_Insert_withSchedule  @EquipmentId=:EquipmentId, @FamilyId=:FamilyId,@ScheduleId=:ScheduleId, @CreateUser=:CreateUser ")
                                .SetInt32("EquipmentId", msg.EquipmentId)
                                .SetInt32("FamilyId", msg.FamilyId)
                                .SetInt32("ScheduleId", msg.ScheduleId)
                                .SetString("CreateUser", msg.CreateUser)
                                .ExecuteUpdate();
                    }
                }
                catch (Exception ex)
                {
                    result = -1;
                }
            }
            return result;
        }

        public IList<ScheduleCommentEntity> GetCommentsByScheduleId(ScheduleCommentMessage msg)
        {
            var result = default(int);
            if (msg != null)
            {
                try
                {
                    var whereStr = " com.ScheduleId = " + msg.ScheduleId;
                    var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Comments_Get @WHERE=:WHERE ")
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<ScheduleCommentEntity>());
                    return query.List<ScheduleCommentEntity>();

                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            return null;
        }

        public int UpdateComments(ScheduleCommentMessage msg)
        {
            var result = default(int);
            if (msg != null)
            {
                try
                {
                    var query = _mcSession.CreateSQLQuery(
                                @" EXEC Schedule_Comment_Insert @Id=:Id, @ScheduleId=:ScheduleId, @UserId=:UserId,@Comment=:Comment, @VedioPath=:VedioPath,@ImagePath=:ImagePath ")
                                .SetInt32("Id", 0)
                                .SetInt32("ScheduleId", msg.ScheduleId)
                                .SetInt32("UserId", msg.UserId)
                                .SetString("Comment", msg.Comment)
                                .SetString("VedioPath", msg.VedioPath)
                                .SetString("ImagePath", msg.ImagePath)
                                .ExecuteUpdate();
                }
                catch (Exception ex)
                {
                    result = -1;
                }
            }
            return result;
        }

        /// <summary>
        /// 获取某一评论的所以回复
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IList<ScheduleCommentReplyEntity> GetCommentReplysByCommentId(ScheduleCommentReplyMessage msg)
        {
            if (msg != null)
            {
                try
                {
                    var whereStr = " ReplyCommentId = " + msg.ReplyCommentId;
                    var query = _mcSession.CreateSQLQuery(@" EXEC Schedule_Comments_Reply_Get @WHERE=:WHERE ")
                            .SetString("WHERE", whereStr)
                            .SetResultTransformer(Transformers.AliasToBean<ScheduleCommentReplyEntity>());
                    return query.List<ScheduleCommentReplyEntity>();

                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            return null;
        }

        /// <summary>
        /// 为评论发表回复
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int AddCommentsReplys(ScheduleCommentReplyMessage msg)
        {
            var result = default(int);
            if (msg != null)
            {
                try
                {
                    var query = _mcSession.CreateSQLQuery(
                                @" EXEC Schedule_Comment_Reply_Insert @Id=:Id, @ReplyCommentId=:ReplyCommentId, @UserId=:UserId,@ReplyContent=:ReplyContent,@ImagePath=:ImagePath,@VedioPath=:VedioPath ")
                                .SetInt32("Id", 0)
                                .SetInt32("ReplyCommentId", msg.ReplyCommentId)
                                .SetInt32("UserId", msg.UserId)
                                .SetString("ReplyContent", msg.ReplyContent)
                                .SetString("ImagePath", msg.ImagePath)
                                .SetString("VedioPath", msg.VedioPath)
                                .ExecuteUpdate();
                }
                catch (Exception ex)
                {
                    result = -1;
                }
            }
            return result;
        }
    }
}
